//
//  SCCarImageUploadVc.m
//  Shuaiche
//
//  Created by xiangtao on 2024/3/22.
//  Copyright © 2024 ShuaiChe. All rights reserved.
//

#import "SCCarImageUploadVc.h"
#import "MBProgressHUD+Add.h"
#import "UIImageView+SCwebImage.h"

@interface SCCarImageUploadVc ()<SCCarAddImageItemCellDelegate>

@property (strong, nonatomic) UILabel *noticeLabel;

@end

@implementation SCCarImageUploadVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (self.maxPics == 0) {
        self.maxPics = 16;
    }
        
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
    [self.collectionView addGestureRecognizer:press];
    
    [self createSingleImageModel];
        
    [self initView];
    
    [self.collectionView reloadData];
}

- (void)createSingleImageModel {
    SCCarAddImageModel *model = [[SCCarAddImageModel alloc] init];
    model.isShowAll = YES;
    NSMutableArray *imagesArray = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *showImagesArray = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary *dic in self.preShows) {
        NSString *title = [dic objectForKey:@"title" defaultValue:nil];
        if (self.imageUploadType == ImageUploadTypeOther) {
            if ([title isEqualToString:@"OTHER_PIC"] ) {
                SCCarAddImageItemModel *itemModel = [[SCCarAddImageItemModel alloc] init];
                itemModel.title = @"OTHER_PIC";
                [itemModel addSelecteImage:nil withPath:dic[kPicUrl]];
                [imagesArray addObject:itemModel];
                [showImagesArray addObject:itemModel];
            }
        } else if (self.imageUploadType == ImageUploadTypeCar) {
            if (title == nil || [title isEqualToString:@"CAR_PIC"] ) {
                SCCarAddImageItemModel *itemModel = [[SCCarAddImageItemModel alloc] init];
                itemModel.title = @"CAR_PIC";
                [itemModel addSelecteImage:nil withPath:dic[kPicUrl]];
                [imagesArray addObject:itemModel];
                [showImagesArray addObject:itemModel];
            }
        }
    }
    [showImagesArray addObject:[SCCarAddImageItemModel addModel]];
    model.imagesArray = imagesArray;
    model.showImagesArray = showImagesArray;
    [self.dataSource addObject:model];
    self.currentModel = model;
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.collectionView.frame = CGRectMake(0, 30, kSCScreenWidth, self.frame.size.height-30);
}

- (void)setNotice:(NSString *)notice
{
    _notice = notice;
    _noticeLabel.text = _notice;
}

- (void)initView {
    UIView *noticeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, 30)];
    noticeView.backgroundColor = SC_HEX(0xFEFCEB);
    [self.view addSubview:noticeView];
    
    UIImageView *noticeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 7.5, 15, 15)];
    noticeIcon.image = [UIImage imageNamed:@"icon_time_tip"];
    [noticeView addSubview:noticeIcon];
    
    _noticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, kSCScreenWidth-50, 30)];
    _noticeLabel.text = self.notice;
    _noticeLabel.textColor = SC_HEX(0xF96A0E);
    _noticeLabel.font = SC_FONT(12);
    [noticeView addSubview:_noticeLabel];
}

- (void)showActionSheet {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showCamera];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showPhotoAlume];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)configureCollectionView{
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 14, 14, 0);
    self.collectionView.alwaysBounceVertical = YES;
    [self registerNibCellName:@"SCCarAddImageItemCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
}

- (void)saveBtnClicked {
    
    NSMutableArray *marray = [NSMutableArray arrayWithCapacity:0];
    for (int j = 0; j < self.dataSource.count; j++) {
        SCCarAddImageModel *model = self.dataSource[j];
        for (int i = 0; i < model.imagesArray.count; i++) {
            SCCarAddImageItemModel *imageModel = model.imagesArray[i];
            if (!imageModel.isAddButton) {
                [marray addObject:imageModel];
                imageModel.positionIndex = [NSIndexPath indexPathForRow:i inSection:j];
            }
        }
    }
    
    if (marray.count < 1) {
        [MBProgressHUD showTip:@"请选择图片" toView:nil];
        return;
    }
    
    // unionPics:
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"上传图片中,请稍等..." toView:nil];
    [SCImageUploadManager startUploadImages:marray completion:^(NSArray * _Nonnull picUrls,NSString *errorString) {
        if (picUrls) {
            int start = 0;
            BOOL shouldAddUnionId = self.dataSource.count > 1;
            [marray removeAllObjects];
            NSMutableArray *mainPics = [NSMutableArray array];
            for (SCCarAddImageModel *model in self.dataSource) {
                for (int i = 0; i < model.imagesArray.count; i++) {
                    SCCarAddImageItemModel *imageModel = model.imagesArray[i];
                    if (!imageModel.isAddButton) {
                        if (start > picUrls.count-1) {
                            break;
                        }
                        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
                        [dic setValue:picUrls[start] forKey:kPicUrl];
                        if (shouldAddUnionId) {
                            [dic setValue:@(model.unionId) forKey:kUnionId];
                        }
                        [marray addObject:dic];
                        if (i == 0 && model.unionId > 0) {
                            NSString *pic = [NSString stringWithFormat:@"%zd#%@",model.unionId,picUrls[start]];
                            if (model.isOfficial) {
                                [mainPics insertObject:pic atIndex:0];
                            } else {
                                [mainPics addObject:pic];
                            }
                        }
                        start++;
                    }
                }
            }
            NSString *mainPicsString = [mainPics componentsJoinedByString:@","];
            if (self.completion) {
                self.completion(marray, mainPicsString);
            }
            [hud switchShowSuccess:@"上传图片成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [hud switchShowError:errorString];
        }
        [self.collectionView reloadData];
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SCCarAddImageModel *model = self.dataSource[section];
    if (model.isShowAll) {
        return MIN(model.showImagesArray.count,16);
    }
    return 0;
}

- (UICollectionViewLayout *)collectionViewLayout {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(floorf((kSCScreenWidth - 52) /4), floorf((kSCScreenWidth - 52) /4));
    flowLayout.minimumLineSpacing = 8;
    return flowLayout;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
    footer.backgroundColor = SC_Color_Separator;
    return footer;
}

- (void)folderWithModel:(SCCarAddImageModel *)model inSection:(NSInteger)sec {
    if (self.isDraging) {
        return;
    }
    model.isShowAll = !model.isShowAll;
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:sec]];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    SCCarAddImageModel *model = self.dataSource[section];
    if (model.isShowAll) {
        return UIEdgeInsetsMake(10, 0, 0, 10);
    }
    return UIEdgeInsetsMake(0, 0, 0, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SCCarAddImageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SCCarAddImageItemCell" forIndexPath:indexPath];
    cell.positionName.hidden = YES;
    cell.delegate = self;
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    if (indexPath.row == 0) {
        cell.mainPicTag.hidden = itemModel.isAddButton;
    } else {
        cell.mainPicTag.hidden = YES;
    }
    cell.deleteBtn.hidden = itemModel.isAddButton;
    if (itemModel.imageUrlPath) {
        [cell.imageView sc_setImageWithPath:itemModel.imageUrlPath];
    } else {
        cell.imageView.image = itemModel.image;
    }
    NSLog(@"cell刷新了");
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    if (itemModel.isAddButton) {
        self.currentModel = model;
        [self showActionSheet];
    } else {
        SCCarImageEditViewController *edit = [[SCCarImageEditViewController alloc] init];
        if (!itemModel.image) {
            SCCarAddImageItemCell *cell = (SCCarAddImageItemCell *)[collectionView cellForItemAtIndexPath:indexPath];
            itemModel.image = cell.imageView.image;
        }
        if (!itemModel.image) {
            [MBProgressHUD showError:@"暂未获取到图片"];
            return;
        }
        edit.editImage = itemModel.image;
        [self.navigationController pushViewController:edit animated:YES];
        edit.reloadBlock = ^(UIImage *image,BOOL isProcess) {
            if (isProcess) {
                itemModel.imageUrlPath = nil;
                itemModel.asset = nil;
            }
            itemModel.image = image;
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
        };
        
        edit.deleteBlock = ^{
            [model.showImagesArray removeObject:itemModel];
            [model.imagesArray removeObject:itemModel];
            model.selectNormalCount --;
//            [self.currentModel.showImagesArray removeObject:itemModel];
//            [self.currentModel.imagesArray removeObject:itemModel];
//            self.currentModel.selectNormalCount--;
//            [self.collectionView reloadData];
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
        };
        
        edit.toMainPicBlock = ^{
            [model.showImagesArray removeObject:itemModel];
            [model.showImagesArray insertObject:itemModel atIndex:0];
            [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
            
            [model.imagesArray removeObject:itemModel];
            [model.imagesArray insertObject:itemModel atIndex:0];
        };
    }
}

#pragma mark - SCCarAddImageItemCellDelegate
- (void)SCCarAddImageItemCellDidDeletePic:(SCCarAddImageItemCell *)cell
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    [model.showImagesArray removeObject:itemModel];
    [model.imagesArray removeObject:itemModel];
    model.selectNormalCount --;
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
    
}

#pragma mark -- Photo Fetch

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<UIImagePickerControllerInfoKey, id> *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:nil];
    SCCarAddImageItemModel *addModel = self.currentModel.showImagesArray.lastObject;
    if (addModel.isAddButton) {
        [self.currentModel.showImagesArray removeLastObject];
    }
    SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
    model.title = self.imageUploadType == ImageUploadTypeOther ? @"OTHER_PIC":@"CAR_PIC";
    model.image = image;
    model.fillImage = YES;
    self.currentModel.selectNormalCount++;
    [self.currentModel.showImagesArray addObject:model];
    [self.currentModel.showImagesArray addObject:addModel];
    [self.currentModel.imagesArray addObject:model];
    [self.collectionView reloadData];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    SCCarAddImageItemModel *addModel = self.currentModel.showImagesArray.lastObject;
    if (addModel.isAddButton) {
        [self.currentModel.showImagesArray removeObject:addModel];
    }
    for (NSInteger i = 0; i < photos.count; i++) {
        UIImage *image = photos[i];
        PHAsset *asset = assets[i];
        SCCarAddImageItemModel *model = [[SCCarAddImageItemModel alloc] init];
        model.title = self.imageUploadType == ImageUploadTypeOther ? @"OTHER_PIC":@"CAR_PIC";
        [model addSelecteImage:image withPath:nil];
        model.asset = asset;
        [self.currentModel.showImagesArray addObject:model];
        [self.currentModel.imagesArray addObject:model];
        self.currentModel.selectNormalCount++;
    }
    [self.currentModel.showImagesArray addObject:addModel];
    [self.collectionView reloadData];
    NSMutableArray *mAssetsAry = [NSMutableArray arrayWithArray:self.currentModel.selectedAssets];
    [mAssetsAry addObjectsFromArray:assets];
    self.currentModel.selectedAssets = mAssetsAry;
}

// 拖拽
- (void)longPressGesture:(UILongPressGestureRecognizer *)longPress {
    CGPoint point = [longPress locationInView:self.collectionView];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    static UICollectionViewCell *cell = nil;
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:{
            if (!indexPath) {
                break;
            }
            self.isDraging = YES;
            if ([self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath]) {
                cell = [self.collectionView cellForItemAtIndexPath:indexPath];
                [UIView animateWithDuration:.25 animations:^{
                    cell.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
                }];
            }
        }
            break;
        case UIGestureRecognizerStateChanged:
            [self.collectionView updateInteractiveMovementTargetPosition:point];
            break;
        case UIGestureRecognizerStateEnded: {
            [self.collectionView endInteractiveMovement];
            cell.transform = CGAffineTransformMakeScale(1.f, 1.f);
        }
            break;
        default:{
            //取消移动
            self.isDraging = NO;
            [self.collectionView cancelInteractiveMovement];
            cell.transform = CGAffineTransformMakeScale(1.f, 1.f);
        }
            break;
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath  {
    
    SCCarAddImageModel *model = self.dataSource[indexPath.section];
    SCCarAddImageItemModel *itemModel = model.showImagesArray[indexPath.row];
    if (itemModel.isAddButton) {
        return NO;
    }

    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath
           toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    if (sourceIndexPath.section != destinationIndexPath.section) {
        SCCarAddImageModel *desModel = [self.dataSource objectAtIndex:destinationIndexPath.section];
        if (desModel.showImagesArray.count < 17) {
            SCCarAddImageModel *model = [self.dataSource objectAtIndex:sourceIndexPath.section];
            SCCarAddImageItemModel *itemModel = model.showImagesArray[sourceIndexPath.item];
            NSInteger item = MIN(desModel.showImagesArray.count-1, destinationIndexPath.item);
            [model.showImagesArray removeObjectAtIndex:sourceIndexPath.item];
            //            [desModel.showImagesArray insertObject:itemModel atIndex:destinationIndexPath.item];

            [desModel.showImagesArray insertObject:itemModel atIndex:item];
            item = MIN(desModel.imagesArray.count, destinationIndexPath.item);
            
            [model.imagesArray removeObjectAtIndex:sourceIndexPath.item];
//            [desModel.imagesArray insertObject:itemModel atIndex:destinationIndexPath.item];
            [desModel.imagesArray insertObject:itemModel atIndex:item];
            model.selectNormalCount--;
            desModel.selectNormalCount++;
        }
        NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
        [indexSet addIndex:sourceIndexPath.section];
        [indexSet addIndex:destinationIndexPath.section];
        [UIView performWithoutAnimation:^{
            [collectionView reloadSections:indexSet];
        }];

    } else {
        
        SCCarAddImageModel *model = [self.dataSource objectAtIndex:sourceIndexPath.section];
        SCCarAddImageItemModel *itemModel = model.showImagesArray[sourceIndexPath.item];
        [model.showImagesArray removeObject:itemModel];
        [model.imagesArray removeObject:itemModel];
        if (destinationIndexPath.item == model.showImagesArray.count) {
            [model.showImagesArray insertObject:itemModel atIndex:destinationIndexPath.item - 1];
            [collectionView reloadSections:[NSIndexSet indexSetWithIndex:sourceIndexPath.section]];
            [model.imagesArray insertObject:itemModel atIndex:destinationIndexPath.item - 1];
        } else {
            [model.showImagesArray insertObject:itemModel atIndex:destinationIndexPath.item];
            [model.imagesArray insertObject:itemModel atIndex:destinationIndexPath.item];
            if (destinationIndexPath.item == 0 || sourceIndexPath.item == 0) {
                [collectionView reloadSections:[NSIndexSet indexSetWithIndex:sourceIndexPath.section]];
            }
        }
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isDraging = NO;
    });
}

- (void)showPhotoAlume {
    [self presetnPhotoAlume:17 - self.currentModel.showImagesArray.count];
}

- (void)showCamera {
    [self dismissViewControllerAnimated:NO completion:nil];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        // picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (void)presetnPhotoAlume:(NSInteger)count {
    
    TZImagePickerController *imagePickController = [[TZImagePickerController alloc] initWithMaxImagesCount:count delegate:self];
//    imagePickController.minImagesCount = 1;
    //是否 在相册中显示拍照按钮
    imagePickController.allowTakePicture = NO;
    //是否可以选择显示原图
    imagePickController.allowPickingOriginalPhoto = YES;
    //是否 在相册中可以选择视频
    imagePickController.allowPickingVideo = NO;
//    imagePickController.showSelectBtn = YES;
    imagePickController.naviBgColor = [UIColor whiteColor];
    imagePickController.naviTitleColor = [UIColor blackColor];
    imagePickController.barItemTextColor = [UIColor blackColor];
    imagePickController.statusBarStyle = UIStatusBarStyleDefault;
    //    imagePickController.selectedAssets = _currentModel.selectedAssets;
    imagePickController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickController.navLeftBarButtonSettingBlock = ^(UIButton *lefyButton){
        [lefyButton setImage:[UIImage imageNamed:@"back_icon"] forState:UIControlStateNormal];
    };
    [self presentViewController:imagePickController animated:YES completion:nil];
}

- (NSString *)datePath{
    if(!_datePath){
        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMM"];
        NSString *datePath = [dateFormatter stringFromDate:date];
        datePath = [NSString stringWithFormat:@"img/%@",datePath];
        _datePath = datePath;
    }
    return _datePath;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
